﻿/*
	PlayerMotor - Takes information from the PlayerController and processes it.
*/

using UnityEngine;
using System.Collections;

public class PlayerMotor : MonoBehaviour {

	public static PlayerMotor instance;

	public float moveSpeed = 10.0f;
	public Vector3 moveVector{get; set;}

	public float gravity = 32.0f;
	public float terminalVelocity = 32f;
	public float verticalVelocity {get; set;}

	public float jumpSpeed = 6.0f;

	void Awake(){
		instance = this;
	}

	public void UpdateMotor(){
		AlignSpriteToCamera();
		ProcessMotion();
	}

	void ProcessMotion(){
		moveVector = transform.TransformDirection(moveVector);

		if(moveVector.magnitude > 1)
			moveVector = Vector3.Normalize(moveVector);

		moveVector *= moveSpeed;

		moveVector = new Vector3(moveVector.x, verticalVelocity, moveVector.z);

		ApplyGravity();

		PlayerController.characterController.Move(moveVector * Time.deltaTime);
	}

	void AlignSpriteToCamera(){
		if(moveVector.x != 0 || moveVector.y != 0){
			Transform spriteTransform = GameObject.FindGameObjectWithTag("Player").transform.Find("PlayerSprite").transform;
			//spriteTransform.rotation = Quaternion.Euler(spriteTransform.eulerAngles.x, Camera.main.transform.eulerAngles.y, spriteTransform.eulerAngles.z);
		}
	}

	void ApplyGravity(){
		if(moveVector.y > -terminalVelocity){
			moveVector = new Vector3(moveVector.x, moveVector.y - gravity * Time.deltaTime, moveVector.z);
		}

		if(PlayerController.characterController.isGrounded && moveVector.y < -1){
			moveVector = new Vector3(moveVector.x, -1, moveVector.z);
		}
	}

	public void Jump(){
		if(PlayerController.characterController.isGrounded){
			verticalVelocity = jumpSpeed;
		}
	}

	void OnControllerColliderHit(ControllerColliderHit hit){
		if(hit.gameObject.CompareTag("SpearTrap")){
			Vector3 normal = hit.normal;
			if(normal.y > 0.1){	//if > 0 then player is on top of something, if < 0 player is under something.
				Debug.Log("Ouch!");
				Vector3 dir = new Vector3(moveVector.x, 5, -5);
				//dir = dir * -1;
				dir = transform.TransformDirection(dir);
				if(dir.magnitude > 1)
					dir = Vector3.Normalize(dir);
				dir = dir * 250;

				PlayerController.characterController.Move(dir * Time.deltaTime);
			}
		}
		if(hit.gameObject.CompareTag("Coin")){
			//add 1 to coins
			PlayerController.instance.coins += 1;
			Destroy(hit.gameObject);
		}
	}
}
